#!/bin/sh

die() {
  echo "fatal error ($1), aborting." >&2
  exit 1
}


# Carefully try to clean up the directory structures we create for samba.
# We go through extra contortions here to minimize the chances that a bug
# (or a deliberate security attack) will cause us to accidentally rm -rf
# important stuff or start with special files in the wrong places.
cleanup() {
  (
    echo "cleaning up"
    random=$(
      dd if=/dev/urandom bs=20 count=1 2>/dev/null |
      sha1sum |
      { read sum junk; echo "$sum"; }
    )
    D=clean.$random.$(date +%s).$$
    for d in /var/lock/samba/subsys /tmp/samba/sockets; do
      dir=$(dirname "$d")
      if [ -d "$dir" ]; then
        cd "$dir" || die 'cd $dir'
        mkdir "$D"
        [ -e "$d" ] && mv "$d" "$D"
        rm -rf "$D" || die rm-rf
      fi
    done
    umount-subdirs-of /chroot/samba
    return 0
  )
}

mounts() {
  cd /chroot/samba && \
  mount -o bind /var/media var/media && \
  mount -o bind /usr/lib usr/lib && \
  mount -o bind /lib lib && \
  mount -o bind /var/lock/samba var/lock && \
  mount -o bind /tmp/samba tmp
}

case "$1" in
  start)
    if is-storage-box; then
      cleanup || die 'start failed'
      mkdir -p /var/lock/samba/subsys /tmp/samba/sockets && \
      chown video.video /var/lock/samba/subsys /tmp/samba && \
      chown video.video /tmp/samba/sockets && \
      mounts || die 'mounts failed'
      chmod 0750 /tmp/samba/sockets && \
      cd /chroot/samba/var/media && (
        ionice -c 3 -n 7 chg_mod_own --uid video --gid video --mode_dir 0775 \
          --mode_file 0664 tv videos pictures music
      ) || die 'prepare environment failed'
      babysit 60 ionice -c 3 -n 7 smbd -F -D -S 2>&1 | logos smbd &
      babysit 60 nmbd -F -D -S 2>&1 | logos nmbd &
    fi 2>&1 | logos smbd &  # run in background to avoid slowing boot
    ;;
  stop)
    # we have to kill the babysitter too, because smbd eats the SIGTERM
    # exit code and returns 1 instead, so babysit thinks it needs to
    # restart.
    pkillwait -f 'babysit 60 smbd'
    pkillwait -f 'babysit 60 nmbd'
    pkillwait -x smbd
    pkillwait -x nmbd
    if is-storage-box; then
      cleanup
    fi
    ;;
  restart)
    $0 stop; $0 start
    ;;
  reload)
    pids=$(pgrep -x smbd)
    [ -n "$pids" ] && kill -1 $pids
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|reload}"
    exit 1
esac
